﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using GRC_TPE_WebApp.Model;
using System.Web.Security;
using System.Security.Cryptography;
using System.Text;

namespace GRC_TPE_WebApp.Controller
{
    public static class UserController
    {
        /// <summary>
        /// Méthode de connexion d'un utilisateur
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns>Retourne le nom et le prénom</returns>
        public static string[] Connect(string username, string password)
        {
            try
            {
                string[] ret = null;

                string encryptedPassword = FormsAuthentication.HashPasswordForStoringInConfigFile(password,"SHA1");

                Model_GRC_TPEContainer database = new Model_GRC_TPEContainer();

                List<User> existingUsers = (from usr in database.UserSet
                                            where usr.Username == username && usr.Password == encryptedPassword
                                            select usr).ToList();

                if (existingUsers.Count == 1)
                {
                    ret = new string[4];
                    ret[0] = existingUsers.First().Firstname;
                    ret[1] = existingUsers.First().Lastname;
                    ret[2] = existingUsers.First().Type;
                    ret[3] = existingUsers.First().Id.ToString();
                }

                return ret;
            }
            catch (Exception ex)
            {
                return null;
            }
        }

        /// <summary>
        /// Méthode de modification d'un utilisateur en base
        /// </summary>
        /// <param name="idUser"></param>
        /// <param name="lastname"></param>
        /// <param name="firstname"></param>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public static string EditUser(int idUser, String lastname, String firstname, String username, String password, String type)
        {
            try
            {
                string ret = string.Empty;

                Model_GRC_TPEContainer database = new Model_GRC_TPEContainer();

                User currentUser = (from user in database.UserSet
                                       where user.Id == idUser
                                       select user).First();

                currentUser.Lastname = lastname;
                currentUser.Firstname = firstname;
                currentUser.Username = username;

                if (!string.IsNullOrEmpty(password))
                    currentUser.Password = FormsAuthentication.HashPasswordForStoringInConfigFile(password, "SHA1");

                currentUser.Type = type;


                database.SaveChanges();

                ret = "No error";

                return ret;
            }
            catch (Exception ex)
            {
                return "Erreur lors de la mise à jour du user";
            }
        }

        /// <summary>
        /// Méthode d'ajout un utilisateur en base
        /// </summary>
        /// <param name="lastname"></param>
        /// <param name="firstname"></param>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public static string AddUser(String lastname,String firstname, String username, String password, String type)
        {
            try
            {
                string ret = string.Empty;

                Model_GRC_TPEContainer database = new Model_GRC_TPEContainer();

                //Création d'un utilisateur temporaire, afin d'effectuer l'insertion en base
                User currentUser = new User();

                //Ajout des paramètres à l'utilisateur courant
                currentUser.Lastname = lastname;
                currentUser.Firstname = firstname;
                currentUser.Username = username;
                currentUser.Password = FormsAuthentication.HashPasswordForStoringInConfigFile(password, "SHA1");
                currentUser.Type = type;
                
                //Ajout en base
                database.AddToUserSet(currentUser);

                //Commit
                database.SaveChanges();

                ret = "No error";

                return ret;
            }
            catch (Exception ex)
            {
                return "Erreur lors de l'ajout de l'utilisateur";
            }
        }

        /// <summary>
        /// Méthode retournant les champs de l'utilisateur sous forme d'un tableau
        /// </summary>
        /// <param name="idUser"></param>
        /// <returns></returns>
        public static string[] GetUserFields(int idUser)
        {
            try
            {
                string[] ret = null;

                Model_GRC_TPEContainer database = new Model_GRC_TPEContainer();

                /// récupération de l'utilisateur par son id
                User existingUser = (from usr in database.UserSet
                                    where usr.Id == idUser
                                    select usr).First();

                if (existingUser != null)
                {
                    ret = new string[5];

                    ret[0] = existingUser.Lastname;
                    ret[1] = existingUser.Firstname;
                    ret[2] = existingUser.Username;
                    ret[3] = existingUser.Password;
                    ret[4] = existingUser.Type;
                }
                else
                {
                    ret = new string[1];
                    ret[0] = String.Format("L'utilisateur d'id '{0}' n'existe pas.", idUser);
                }

                return ret;
            }
            catch (Exception ex)
            {
                string[] ret = new string[1];

                ret[0] = String.Format("Une erreur est survenue lors de la récupération de l'utilisateur d'id '{0}' en base.", idUser);

                return ret;
            }
        }

        /// <summary>
        /// Suppression d'un utilisateur
        /// </summary>
        /// <param name="idUser"></param>
        /// <returns></returns>
        public static string DeleteUser(int idUser)
        {
            try
            {
                string ret = string.Empty;

                Model_GRC_TPEContainer database = new Model_GRC_TPEContainer();

                /// récupération de l'utilisateur par son id
                User existingUser = (from user in database.UserSet
                                     where user.Id == idUser
                                        select user).First();

                if (existingUser != null)
                {
                    database.DeleteObject(existingUser);
                    database.SaveChanges();
                }
                else
                {
                    ret = String.Format("L'utilisateur d'id '{0}' n'existe pas.", idUser);
                }

                ret = "No error";

                return ret;
            }
            catch (Exception ex)
            {
                return string.Format("Erreur lors de la suppression de l'utilisateur d'id '{0}'.", idUser);
            }
        }
    }
}